package list.model;

import list.control.MysqlLink;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 * Created by ZhipengLi.
 */
public class Telephone extends MysqlLink {
    private static final String TABLE = "telephone";

    private int id;
    private String phone_number;
    private int contact_id;
    private String type;
    private String remark;

    public Telephone(int id) {
        this.id = id;
    }

    private Telephone(int id, String phone_number, int contact_id, String type, String remark) {
        this.id = id;
        this.phone_number = phone_number;
        this.contact_id = contact_id;
        this.type = type;
        this.remark = remark;
    }

    public static boolean insert(int contact_id, String phone_number, String type, String remark) {
        return insert(TABLE, toArray("phone_number", "type", "remark"), toArray(phone_number, type, remark));
    }

    public static boolean delete(int contact_id, int id) {
        return delete(TABLE, equal("contact_id", id));
    }

    public static boolean update(int contact_id, int id, String phone_number, String type, String remark) {
        return update(TABLE, toArray("phone_number", "type", "remark"), toArray(phone_number, type, remark), equal("id", id));
    }

    public static Telephone[] select(int contact_id) {
        ResultSet resultSet = select(TABLE, ALL, equal("contact_id", contact_id));
        if (null != resultSet) {
            try {
                ArrayList<Telephone> telephones = new ArrayList<>();
                while (resultSet.next()) {
                    int id = resultSet.getInt("id");
                    String phone_number = resultSet.getString("phone_number");
                    String type = resultSet.getString("type");
                    String remark = resultSet.getString("remark");
                    telephones.add(new Telephone(id, phone_number, contact_id, type, remark));
                }
                resultSet.close();
                if (0 < telephones.size()) {
                    Telephone[] telephoneList = new Telephone[telephones.size()];
                    telephones.toArray(telephoneList);
                    return telephoneList;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public int getId() {
        return id;
    }

    public String getPhone_number() {
        return phone_number;
    }

    public int getContact_id() {
        return contact_id;
    }

    public String getType() {
        return type;
    }

    public String getRemark() {
        return remark;
    }
}
